package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;


@Component
@Slf4j
public class orderTask {

    @Autowired
    private OrderMapper orderMapper;
    //1、每隔1分钟对订单表中待付款的订单进行查询，如果超时15分钟则取消该订单
    @Scheduled(cron = "0 0/1 * * * ? ")
    public void processTimeoutOrder(){
        log.info("定时处理超时未支付程序执行");
        //根据订单的状态和时间来获取超时未支付的订单信息，将当前的时间减去15分钟，得到超时时间
        Integer status = Orders.PENDING_PAYMENT;
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);
        List<Orders> ordersList = orderMapper.queryTimeoutOrderList(status,time);
        //循环遍历订单信息，设置更新的状态
        if(ordersList != null && ordersList.size() > 0) {
            for (Orders orders : ordersList) {
                //创建一个新的更新对象，用于更新订单数据
                Orders updateOrder = new Orders();
                updateOrder.setId(orders.getId());
                updateOrder.setStatus(Orders.CANCELLED);
                updateOrder.setCancelReason("支付超时");
                updateOrder.setCancelTime(LocalDateTime.now());
                orderMapper.update(updateOrder);
            }
        }
    }

    //2、每次在凌晨一点检查前一天的订单，如果订单的状态为派送中，则进行取消订单
    @Scheduled(cron = "0 0 1 * * ? ")
    public void processDeliveryOrder(){
        log.info("定时处理派送中的订单程序执行");
        Integer status = Orders.DELIVERY_IN_PROGRESS;
        LocalDateTime time = LocalDateTime.now().minusMinutes(60);
        List<Orders> ordersList = orderMapper.queryTimeoutOrderList(status,time);
        if (ordersList != null && ordersList.size() > 0) {
            for (Orders orders : ordersList){
                Orders updateOrder = new Orders();
                updateOrder.setId(orders.getId());
                updateOrder.setStatus(Orders.CANCELLED);
                updateOrder.setCancelReason("派送超时");
                updateOrder.setCancelTime(LocalDateTime.now());
                orderMapper.update(updateOrder);
            }
        }
    }
}
